﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using 机器组和机器编辑.modify;

namespace 机器组和机器编辑
{
    public partial class MainForm : Form
    {

        // 用于ID自动增长的变量
        private int nextMachineGroupID = 1; //机器组ID自增长
        private int machineNextID = 1; //机器ID自增长

        // XML文件保存路径
        private const string MachineGroupsXmlPath = @"C:\Users\24929\Desktop\机器组和机器编辑\Config\MachineGroupConfiguration.xml"; // 机器组配置文件
        private const string MachinesXmlPath = @"C:\Users\24929\Desktop\机器组和机器编辑\Config\MachineConfig.xml"; // 机器配置文件

        // XML根元素名称
        private const string MachineGroupsRoot = "Machine";
        private const string MachineGroupElement = "MachineGroup"; 

        private void SaveMachineGroupsToXml()
        {
            try
            {
                XDocument doc = new XDocument(
                    new XElement(MachineGroupElement,
                        from DataGridViewRow row in dataGridView1.Rows
                        where !row.IsNewRow
                        select new XElement(MachineGroupElement,
                            new XAttribute("id", GetSafeCellValue(row, "groupID", "0")),
                            new XAttribute("name", GetSafeCellValue(row, "groupName", "")),
                            new XAttribute("configuration", row.Cells["groupConfiguration"].Value is bool b && b ? "true" : "false"), // 示例值
                            new XAttribute("language", row.Cells["language"].Value?.ToString() ?? ""),
                            new XAttribute("type", row.Cells["groupType"].Value?.ToString() ?? "")
                        )
                    )
                );

                doc.Save(MachineGroupsXmlPath);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存机器组数据时出错: {ex.Message}");
            }
        }
        private void SaveTheMachineAsXml()
        {
            try
            {
                XDocument doc = new XDocument(
                    new XElement(MachineGroupsRoot,
                        from DataGridViewRow row in dataGridView2.Rows
                        where !row.IsNewRow
                        select new XElement(MachineGroupsRoot,
                            new XAttribute("display", row.Cells["display"].Value is bool a && a ? "true" : "false"),  //显示
                            new XAttribute("id", GetSafeCellValue(row, "ID", "0")), //编号
                            new XAttribute("name", GetSafeCellValue(row, "name", "")), //机器名称
                            new XAttribute("numbr", GetSafeCellValue(row, "numbr", "")), //机器编号
                            new XAttribute("modelNumder", row.Cells["modelNumder"].Value?.ToString() ?? ""), //机器型号_编号
                             new XAttribute("online", row.Cells["online"].Value is bool b && b ? "true" : "false"), // 在线
                            new XAttribute("group", row.Cells["group"].Value?.ToString() ?? ""), //机器组名称
                            new XAttribute("configuration", row.Cells["configuration"].Value?.ToString() ?? "")  //配置项
                        )
                    )
                );

                doc.Save(MachinesXmlPath);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存机器组数据时出错: {ex.Message}");
            }
        }

        // 辅助方法：安全获取单元格值
        private string GetSafeCellValue(DataGridViewRow row, string columnName, string defaultValue)
        {
            if (row.Cells[columnName] == null || row.Cells[columnName].Value == null)
                return defaultValue;

            return row.Cells[columnName].Value.ToString() ?? defaultValue;
        }
        public MainForm()
        {
            InitializeComponent();
            LoadDataFromXml();
            LoadDataMachinesXml();
            dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        private void 添加(object sender, EventArgs e)
        {
            if (cmsMain.SourceControl == dataGridView1)
                //连接实现机器组添加
                AddMachineGroup();
        }

        private void 编辑(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                int groupId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["groupID"].Value); //拿选中数据的ID
                using (var editForm = new EditForm())
                {
                    editForm.ModifyMachineGroupById(groupId);
                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        // 重新加载XML并刷新表格
                        LoadDataFromXml();
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择要编辑的机器组！");
            }
        }

        private void 删除(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                int groupId = Convert.ToInt32(dataGridView1.CurrentRow.Cells["groupID"].Value);

                // 确认删除
                if (MessageBox.Show("确定要删除该机器组吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DeleteMachineGroupById(groupId);
                    LoadDataFromXml(); // 刷新表格
                    MessageBox.Show("删除成功！");
                }
            }
            else
            {
                MessageBox.Show("请先选择要删除的机器组！");
            }
        }

        // 删除XML中对应ID的节点
        private void DeleteMachineGroupById(int groupId)
        {
            var doc = XDocument.Load(MachineGroupsXmlPath);
            var element = doc.Root.Elements("MachineGroup")
                .FirstOrDefault(x => (int)x.Attribute("id") == groupId);
            if (element != null)
            {
                element.Remove();
                doc.Save(MachineGroupsXmlPath);
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) //机器组表格
        {

        }

        private void 文件ToolStripMenuItem_Click(object sender, EventArgs e) //文件功能
        {

        }

        private void Form1_Load(object sender, EventArgs e) //窗体
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)  //顶部菜单栏
        {

        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) //退出功能
        {
            ExitApplication();
        }

        private void ExitApplication()
        {
            //退出功能的实现
            DialogResult result = MessageBox.Show("确定要退出程序吗？", "退出确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
        //机器组添加方法
        private void AddMachineGroup()
        {
            using (var form = new AddConfigurationForm())
            {
                form.NextID = nextMachineGroupID;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    int rowIndex = dataGridView1.Rows.Add();
                    DataGridViewRow newRow = dataGridView1.Rows[rowIndex];

                    // 设置单元格值
                    newRow.Cells["groupID"].Value = nextMachineGroupID++;
                    newRow.Cells["groupName"].Value = form.GroupName;
                    newRow.Cells["groupConfiguration"].Value = form.ConfigurationEnabled;
                    newRow.Cells["language"].Value = form.SelectedLanguage;
                    newRow.Cells["groupType"].Value = form.SelectedType;

                    // 保存到XML
                    SaveMachineGroupsToXml();

                    // 显示成功消息
                    MessageBox.Show("机器组已成功添加！", "操作成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        // 程序启动时加载XML数据
        private void LoadDataFromXml()
        {
            const string xmlPath = @"C:\Users\24929\Desktop\机器组和机器编辑\Config\MachineGroupConfiguration.xml";

            if (!File.Exists(xmlPath))
            {
                // 创建空文件
                CreateDefaultXmlFile(xmlPath);
            }

            try
            {
                if (File.Exists(MachineGroupsXmlPath))
                {
                    XDocument doc = XDocument.Load(MachineGroupsXmlPath);
                    dataGridView1.Rows.Clear();  // 清除现有行

                    // 查找最大ID（防止多行记录重叠）
                    int maxID = doc.Root.Elements()
                        .Select(e => (int?)e.Attribute("id"))
                        .Where(id => id.HasValue)
                        .DefaultIfEmpty(0)
                        .Max() ?? 0;

                    nextMachineGroupID = maxID + 1;  // 设置下一个可用ID

                    foreach (XElement group in doc.Root.Elements())
                    {
                        int rowIndex = dataGridView1.Rows.Add();
                        DataGridViewRow row = dataGridView1.Rows[rowIndex];

                        // 设置单元格值（包括配置状态）
                        int id = (int)group.Attribute("id");
                        row.Cells["groupID"].Value = id;
                        row.Cells["groupName"].Value = group.Attribute("name")?.Value ?? "";

                        // 恢复配置状态
                        bool configValue = false;
                        if (bool.TryParse(group.Attribute("configuration")?.Value, out bool parsedValue))
                            configValue = parsedValue;

                        row.Cells["groupConfiguration"].Value = configValue;

                        row.Cells["language"].Value = group.Attribute("language")?.Value ?? "";
                        row.Cells["groupType"].Value = group.Attribute("type")?.Value ?? "";
                    }
                }
                else
                {
                    CreateDefaultXmlFile(MachineGroupsXmlPath);
                    nextMachineGroupID = 1;  // 如果文件不存在，从1开始
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n\n系统将从空白开始运行",
                    "加载错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                nextMachineGroupID = 1;
            }
        }

        private void CreateDefaultXmlFile(string path)
        {
            try
            {
                new XDocument(
                    new XElement("MachineGroups")
                ).Save(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建XML文件失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void cmsMain_Opening(object sender, CancelEventArgs e) //右键点击事件
        {

        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e) //机器的添加
        {
            AddMachine();
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e) //修改机器
        {
            if (dataGridView2.CurrentRow == null)
            {
                int ID = Convert.ToInt32(dataGridView1.CurrentRow.Cells["ID"].Value); //拿选中数据的ID
                MessageBox.Show("请先选择要修改的机器！");
                return;
            }
            var cellValue = dataGridView2.CurrentRow.Cells["ID"].Value;
            if (cellValue == null || cellValue == DBNull.Value || string.IsNullOrWhiteSpace(cellValue.ToString()))
            {
                MessageBox.Show("选中行没有ID，请检查数据！");
                return;
            }
            int groupId;
            if (!int.TryParse(cellValue.ToString(), out groupId))
            {
                MessageBox.Show("ID格式不正确！");
                return;
            }
            using (var editForm = new ModifyTheMachine())
            {
                editForm.ModifyMachineById(groupId);

                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    LoadDataMachinesXml();
                }
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e) //机器的删除
        {
            if (dataGridView2.CurrentRow != null)
            {
                int groupId = Convert.ToInt32(dataGridView2.CurrentRow.Cells["ID"].Value);

                if (MessageBox.Show("确定删除此机器吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DeleteMachineNextID(groupId);
                    LoadDataMachinesXml();
                    MessageBox.Show("删除成功！");
                }
            }
            else
            {
                MessageBox.Show("请选择要修改的机器");
            }
        }

        private void DeleteMachineNextID(int groupId)
        {
            var doc = XDocument.Load(MachinesXmlPath);
            var element = doc.Root.Elements("Machine").FirstOrDefault(x => (int)x.Attribute("id") == groupId);
            if (element != null)
            {
                element.Remove();
                doc.Save(MachinesXmlPath);
            }
        }

        private void AddMachine()
        {
            using (var form = new MachineAdderForm())
            {
                form.SelectedId = machineNextID;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    int rounded = dataGridView2.Rows.Add();
                    DataGridViewRow row = dataGridView2.Rows[rounded];

                    //表格映射
                    row.Cells["display"].Value = form.SelectedDisplay;
                    row.Cells["ID"].Value = machineNextID++;
                    row.Cells["name"].Value = form.SelectedName;
                    row.Cells["numbr"].Value = form.SelectedNumbr;
                    row.Cells["modelNumder"].Value = form.SelectedModelNumder;
                    row.Cells["online"].Value = form.SelectedOnline;
                    row.Cells["group"].Value = form.SelectedGroup;
                    row.Cells["configuration"].Value = form.SelectedConfiguration;

                    //保存至XML
                    SaveTheMachineAsXml();
                }
            }
        }
        private void LoadDataMachinesXml()
        {
            const string xmlPath = @"C:\Users\24929\Desktop\机器组和机器编辑\Config\MachineConfig.xml";

            if (!File.Exists(xmlPath))
            {
                // 创建空文件
                CreateDefaultXmlFile(xmlPath);
            }

            try
            {
                if (File.Exists(MachinesXmlPath))
                {
                    XDocument doc = XDocument.Load(MachinesXmlPath);
                    dataGridView2.Rows.Clear();  // 清除现有行

                    // 查找最大ID（防止多行记录重叠）
                    int maxID = doc.Root.Elements()
                        .Select(e => (int?)e.Attribute("id"))
                        .Where(id => id.HasValue)
                        .DefaultIfEmpty(0)
                        .Max() ?? 0;

                    machineNextID = maxID + 1;  // 设置下一个可用ID

                    foreach (XElement machine in doc.Root.Elements())
                    {
                        int rowIndex = dataGridView2.Rows.Add();
                        DataGridViewRow row = dataGridView2.Rows[rowIndex];

                        // 读取并映射各属性
                        row.Cells["display"].Value = (machine.Attribute("display")?.Value == "true");
                        row.Cells["ID"].Value = (int?)machine.Attribute("id") ?? 0;
                        row.Cells["name"].Value = machine.Attribute("name")?.Value ?? "";
                        row.Cells["numbr"].Value = machine.Attribute("numbr")?.Value ?? "";
                        row.Cells["modelNumder"].Value = machine.Attribute("modelNumder")?.Value ?? "";
                        row.Cells["online"].Value = (machine.Attribute("online")?.Value == "true");
                        row.Cells["group"].Value = machine.Attribute("group")?.Value ?? "";
                        row.Cells["configuration"].Value = machine.Attribute("configuration")?.Value ?? "";
                    }
                }
                else
                {
                    CreateDefaultXmlFile(MachinesXmlPath);
                    machineNextID = 1;  // 如果文件不存在，从1开始
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n\n系统将从空白开始运行",
                    "加载错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                machineNextID = 1;
            }
        }
        //另存xml
        private void SaveAs_Click_1(object sender, EventArgs e)
        {
            // 创建保存文件对话框
            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "XML 文件 (*.xml)|*.xml|所有文件 (*.*)|*.*";
                saveDialog.Title = "保存机器配置";
                saveDialog.FileName = "MachineConfiguration_" + DateTime.Now.ToString("yyyyMMdd") + ".xml";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveDialog.FileName;

                    try
                    {
                        // 创建一个新的 XML 文档
                        XDocument doc = new XDocument(
                            new XDeclaration("1.0", "utf-8", "yes"),
                            new XElement("MachineConfiguration",
                                new XElement("MachineGroups",
                                    // 从界面获取机器组数据
                                    GetMachineGroupsFromUI()
                                ),
                                new XElement("Machines",
                                    // 从界面获取机器数据
                                    GetMachinesFromUI()
                                )
                            )
                        );

                        // 保存到指定路径
                        doc.Save(filePath);
                        MessageBox.Show($"配置已成功保存到: {filePath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        // 从界面获取机器组数据
        private List<XElement> GetMachineGroupsFromUI()
        {
            var groups = new List<XElement>();

            // 假设界面表格绑定到数据源
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                // 跳过空行
                if (row.IsNewRow) continue;

                groups.Add(new XElement("MachineGroup",
                    new XAttribute("id", row.Cells["GroupID"].Value?.ToString()),
                    new XAttribute("name", row.Cells["GroupName"].Value?.ToString()),
                    new XAttribute("configuration", row.Cells["GroupConfiguration"].Value?.ToString()),
                    new XAttribute("language", row.Cells["Language"].Value?.ToString()),
                    new XAttribute("type", row.Cells["GroupType"].Value?.ToString())
                ));
            }

            return groups;
        }
        
        // 从界面获取机器数据
        private List<XElement> GetMachinesFromUI()
        {
            var machines = new List<XElement>();

            // 假设界面表格绑定到数据源
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                // 跳过空行
                if (row.IsNewRow) continue;

                machines.Add(new XElement("Machine",
                    new XAttribute("display", row.Cells["Display"].Value?.ToString()),
                    new XAttribute("id", row.Cells["ID"].Value?.ToString()),
                    new XAttribute("name", row.Cells["Name"].Value?.ToString()),
                    new XAttribute("numbr", row.Cells["Numbr"].Value?.ToString()),
                    new XAttribute("modelNumber", row.Cells["ModelNumder"].Value?.ToString()),
                    new XAttribute("online", row.Cells["Online"].Value?.ToString()),
                    new XAttribute("group", row.Cells["Group"].Value?.ToString()),
                    new XAttribute("configuration", row.Cells["Configuration"].Value?.ToString())
                ));
            }

            return machines;
        }

        
     
    }
}

// 伪代码：
// 1. 定义主窗体MainForm，包含机器组和机器的增删改查功能。
// 2. 初始化时加载机器组和机器的XML数据到DataGridView。
// 3. 提供添加、编辑、删除机器组的方法，并同步到XML文件。
// 4. 提供添加、编辑、删除机器的方法，并同步到XML文件。
// 5. 提供安全获取单元格值的辅助方法。
// 6. 提供退出程序、创建默认XML文件等通用功能。
// 7. 所有操作均通过窗体交互，数据变更后自动刷新界面。
